window.onload = function () {
  const playerContainer = document.getElementById('playerContainer')
  const audio = document.getElementById('audio')
  const progressBar = document.getElementById('progressBar')
  const progressContainer = document.getElementById('progressContainer')
  const currentTimeDisplay = document.getElementById('currentTime')
  const durationDisplay = document.getElementById('duration')
  const artistStatus = document.getElementById('artistStatus')
  const progressIndicator = document.getElementById('progressIndicator')

  playerContainer.classList.add('paused')

  playerContainer.addEventListener('click', function () {
    if (audio.paused) {
      audio.play()
      playerContainer.classList.remove('paused')
      playerContainer.classList.add('playing')
      artistStatus.textContent = '歌手'
    } else {
      audio.pause()
      playerContainer.classList.remove('playing')
      playerContainer.classList.add('paused')
      artistStatus.textContent = '已暂停'
    }
  })

  audio.addEventListener('timeupdate', function () {
    const currentTime = audio.currentTime
    const duration = audio.duration || 1
    const progressPercent = (currentTime / duration) * 100

    progressBar.style.width = `${progressPercent}%`
    moveProgressIndicator(progressPercent)
    currentTimeDisplay.textContent = formatTime(currentTime)
    if (duration && !isNaN(duration)) {
      durationDisplay.textContent = formatTime(duration)
    }
  })

  progressContainer.addEventListener('click', function (e) {
    const rect = this.getBoundingClientRect()
    const clickPosition = e.clientX - rect.left
    const percent = clickPosition / rect.width
    audio.currentTime = percent * (audio.duration || 0)
  })

  audio.addEventListener('ended', function () {
    playerContainer.classList.remove('playing')
    playerContainer.classList.add('paused')
    progressBar.style.width = '0%'
    moveProgressIndicator(0)
    currentTimeDisplay.textContent = '0:00'
    artistStatus.textContent = '播放结束'
  })

  function formatTime(seconds) {
    seconds = seconds || 0
    const m = Math.floor(seconds / 60)
    const s = Math.floor(seconds % 60)
    return `${m}:${s < 10 ? '0' : ''}${s}`
  }

  audio.addEventListener('loadedmetadata', function () {
    durationDisplay.textContent = formatTime(audio.duration)
  })

  audio.addEventListener('error', function () {
    artistStatus.textContent = '音频加载失败'
    console.error('音频加载错误:', audio.error)
  })

  function moveProgressIndicator(progressPercent) {
    const px = (progressContainer.clientWidth * progressPercent) / 100
    progressIndicator.style.left = `${px}px`
    progressIndicator.style.opacity = progressPercent > 0 && progressPercent < 100 ? 0.85 : 0.3
  }
  moveProgressIndicator(0)
}
